<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;
use App\Helpers\VisitTrait;
use Illuminate\Support\Facades\DB;

class WineProduct extends BaseModel
{
    use VisitTrait;

    protected $table = "wine_product";

    protected $fillable = [
         'youzan_id',
          'name',
          'chname',
          'productCode',
          'code',
          'chateau_id',
          'chateauName',
          'state',
          'letDrink_recom',
          'country_id',
          'subdivision_id',
          'region_id',
          'category',
          'level',
          'win_info',
          'deployment',
          'grape',
          'vintage',
          'upTime',
          'unTime',
          'degree',
          'degree_score',
          'sweetness',
          'acidity',
          'bitter',
          'complexity',
          'Intensity',
          'aftertaste',
          'wine_body',
          'scale',
          'letDrink_intro',
          'averageScore',
          'online',
          'online_at',
          'offline_at',
          'weight',
          'pv',
          'uv',
          'remark',
          'user_id',
          'updater',
          'creator',
          'price',
          'banner',
          'promotion_price',
          'sku',
          'upMaxTime',
          'sell_method',
          'capacity',
          'show_scenes',
          'show_cuisine',
          'taste_id',
          'grading_id',
          'g_region_id' 
    ];

    protected $appends = ['want_drink_count','has_drink_count','order_count'];

    //葡萄酒图片
    public function covers()
    {
        return $this->belongsToMany('App\Model\Resource','sys_resource_table','obj_id',
            'resource_id')->wherePivot('obj_type','product_cover');
    }

    //1.Drink介绍
    public function drink()
    {
        return $this->hasOne('App\Model\WineProductDrink','product_id','id');
    }

    //2.专业品鉴
    public function judge()
    {
        return $this->hasOne('App\Model\WineProductJudge','product_id','id');
    }

    //3.葡萄酒技术信息
    public function technique()
    {
        return $this->hasOne('App\Model\WineProductTechnique','product_id','id');
    }

    //4.专业评分
    public function score()
    {
        return $this->hasOne('App\Model\WineProductScore','product_id','id')
            ->where('type','=','self');
    }

    //国家
    public function country()
    {
        return $this->belongsTo('App\Model\SysCountry','country_id','id');
    }
    //地区
    public function subdivision()
    {
        return $this->belongsTo('App\Model\SysSubdivision','subdivision_id','id');
    }
    //产区
    public function region()
    {
        return $this->belongsTo('App\Model\SysRegion','region_id','id');
    }
    //产区
    public function gRegion()
    {
        return $this->belongsTo('App\Model\SysGRegion','g_region_id','id');
    }

    //所属酒庄
    public function chateau()
    {
        return $this->belongsTo('App\Model\WineChateau','chateau_id','id');
    }

    public function drinkTasteKeywords()
    {
        return $this->hasMany('App\Model\WineDrinkKeywords','product_id','id');
    }

    //消费场景
    public function scenes()
    {
        return $this->hasMany('App\Model\WineProductSceneRelation','product_id')
            ->orderBy('wine_product_scene_relation.id','asc');
//        return $this->belongsToMany('App\Model\WineProductScene','wine_product_scene_relation',
//            'product_id','scene_one_id');
    }

    public function getScenesItemsAttribute()
    {
        $items = [];
        foreach ($this->scenes as $v){
            $items[] = $v->currentScene;
        }
        return $items;
    }

    //关联葡萄酒
    public function relationProducts()
    {
        return $this->belongsToMany('App\Model\WineProduct','wine_product_relation',
            'product_id','obj_id');
    }

    //关联酒庄
    public function relationChateaus()
    {
        return $this->belongsToMany('App\Model\WineChateau','wine_product_chateau_relation',
            'product_id','obj_id');
    }

    //混酿表
    public function blendDeployment()
    {
        return $this->hasMany('App\Model\WineProductDeployment','product_id','id')
            ->orderBy('scale','desc')->orderBy('wine_product_deployment.created_at','asc');
    }
    public function wantDrink()
    {
        return $this->belongsToMany('App\User','t_user_want_drinks','product_id','user_id');
    }
    public function hasDrink()
    {
        return $this->belongsToMany('App\User','t_user_has_drinks','product_id','user_id');

    }
    public function userWantDrink()
    {
        return $this->hasOne('App\Model\WantDrink','product_id','id')
            ->where('t_user_want_drinks.user_id','=',$this->loginUser()?$this->loginUser()->id:0);
    }
    public function userHasDrink()
    {
        return $this->hasOne('App\Model\HasDrink','product_id','id')
            ->where('t_user_has_drinks.user_id','=',$this->loginUser()?$this->loginUser()->id:0);
    }
    public function relationImporters()
    {
        return $this->belongsToMany('App\Model\Importer','wine_product_importer_relations',
            'product_id','importer_id');
    }
    public function relationDealers()
    {
        return $this->belongsToMany('App\Model\Dealer','wine_product_dealer_relations','product_id','dealer_id')
            ->withPivot('show')->withTimestamps();
    }
    //口味定义
    public function wineTastes()
    {
        return $this->belongsTo('App\Model\WineTaste','taste_id','id');
    }
    //产品档次
    public function wineGrading()
    {
        return $this->belongsTo('App\Model\WineGrading','grading_id','id');
    }
    //用户标签
    public function userTags()
    {
        return $this->hasMany('App\Model\WineProductUserTag','product_id','id');
    }
    //菜系
    public function cuisines()
    {
        return $this->hasMany('App\Model\WineProductCuisineRelation','product_id','id');
    }

    public function showDetail()
    {
        $this->load([
            'covers',
            'drink',
            'judge',
            'technique',
            'score',
            'chateau',
            'chateau.produce',
            'country',
            'subdivision',
            'region',
            'gRegion',
            'score.sameScores',
            'userHasDrink',
            'userWantDrink',
            //'scenes',
            'blendDeployment',
            'relationProducts',
            'relationProducts.userHasDrink',
            'relationProducts.userWantDrink',
            'relationProducts.wineGrading',
            'relationProducts.scenes',
            'relationProducts.drinkTasteKeywords',
            'relationImporters',
            'relationDealers',
            'cuisines',
            'scenes',
            'wineTastes',
            'wineGrading',
            'userTags',

            //'relationChateaus',
            // 'chateau.produce'=> function($query){
            //     $query->select('name','chname','logo');
            // },
            // 'country' => function($query){
            //     $query->select('country','chCountry','national_flag');
            // },
            // 'subdivision' => function($query){
            //     $query->select('subdivision','chSubdivision');
            // },
            // 'region' => function($query){
            //     $query->select('region','chRegion');
            // },
            //  'relationProducts' => function($query){
            //     $query->select('wine_product_relation.obj_id as id','name','chname','chateauName','vintage','banner','price','promotion_price');
            // },
            //'relationProducts.covers',
            // 'relationDealers' => function($query){
            //     $query->select(['name','area_name','tel','detail']);
            // }
            // 'relationImporters' => function($query){
            //     $query->select(['name','area_name','tel','detail']);
            // },
        ]);

        $this->append('scenesItems')->setHidden(['scenes']);

    }

    //想喝
    public function getWantDrinkCountAttribute()
    {
        return DB::table('t_user_want_drinks')->where('product_id','=',$this->id)->count();
    }
    //喝过
    public function getHasDrinkCountAttribute()
    {
        return DB::table('t_user_has_drinks')->where('product_id','=',$this->id)->count();
    }
    //订单量
    public function getOrderCountAttribute()
    {
        return DB::table('orders')->where('product_id','=',$this->id)->whereNull('deleted_at')->count();
    }
    //列出进口商id数组
    public static function listImporterIds($product_id)
    {
        return DB::table('wine_product_importer_relations')->where('product_id','=',$product_id)
                ->whereNull('deleted_at')->pluck('importer_id')->toArray();
    }
    //列出经销商数组
    public static function listDealerIds($product_id)
    {
        return DB::table('wine_product_dealer_relations')->where('product_id','=',$product_id)
            ->whereNull('deleted_at')->pluck('dealer_id')->toArray();
    }
    //检查是否存在进口商
    public static function checkImporterExist($importer_id,$product_id)
    {
        return DB::table('wine_product_importer_relations')->where('importer_id','=',$importer_id)
            ->where('product_id','=',$product_id)->whereNull('deleted_at')->count() > 0;
    }
    //检查是否存在经销商
    public static function checkDealerExist($dealer_id,$product_id)
    {
        return DB::table('wine_product_dealer_relations')->where('dealer_id','=',$dealer_id)
                ->where('product_id','=',$product_id)->whereNull('deleted_at')->count() > 0;
    }
    public function beforeSave($input = null)
    {
        //更新酒庄名称
        if ($this->productChateau) {
            $this->chateauName = $this->productChateau->chname;
        }

        //切换上下时更新上下线时间
        if($this->online != $this->getOriginal('online')) {
            if ($this->online == "yes") {
                $this->online_at = Helpers::now();
            }
            if ($this->online == "no") {
                $this->offline_at = Helpers::now();
            }
        }

        return true;
    }

    public static function hot()
    {
        $max = DB::select('SELECT MAX(total),product_id FROM (SELECT COUNT(id) AS total,product_id 
        FROM orders GROUP BY product_id) con');

        if (count($max)>0){
            $item = WineProduct::find($max[0]->product_id);
            return $item;
        }
        return null;
    }
}
